<template>
  <div>
    <div v-for="(item, index) in payList" :key="index" class="pay-block">
      <div class="radio-group">
        <el-radio-group
          v-model="item.smpPayTypeBO.payType"
          @change="handleRadioChange(index, item.smpPayTypeBO.payType)"
        >
          <el-radio
            v-for="item1 in jsList.paymentModeTop"
            :key="item1.dicKey"
            :label="item1.dicKey"
            >{{ item1.dicValue }}</el-radio
          >
        </el-radio-group>
        <div>
          <el-button
            v-if="index === 0"
            plain
            type="single-number-filleted"
            @click="addPayBlock"
            >新增付款条件</el-button
          >
          <el-button
            v-if="index !== 0"
            plain
            type="single-number-filleted"
            @click="removePayBlock(index)"
            >移除付款条件</el-button
          >
          <el-button plain type="single-number-filleted" @click="addRow(index)"
            >新增行</el-button
          >
        </div>
      </div>
      <div class="ccui-multifunctional-table-wrapper">
        <el-table
          :data="item.smpPayTypeItemBOS"
          class="ccui-form-child-table"
          border
          :header-cell-class-name="must"
          lazy
          style="width: 100%"
        >
          <el-table-column type="index" width="80" label="支付次数" />

          <el-table-column prop="materialName" label="规定时间" width="370">
            <template slot-scope="{ row, $index }">
              <el-select
                v-if="item.smpPayTypeBO.payType !== 2"
                class="ccui-form-longInput"
                v-model="row.fixTimeCode"
                placeholder="请选择"
                @change="handleChange(row, $index, 'fixTime')"
              >
                <el-option
                  v-for="item in jsList[
                    $index === 0 ? 'onceFixTimeEnum' : 'fixTimeEnum'
                  ]"
                  :key="item.dicKey"
                  :label="item.dicValue"
                  :value="item.dicKey"
                >
                </el-option>
              </el-select>

              <el-input
                v-if="
                  ![3, 5].includes(row.fixTimeCode) || row.fixTimeCode === 0
                "
                class="pay-input"
                type="text"
                v-model="row.fixTimeLength"
                @blur="testColumn($event, row, 'blur', 'fixTimeLength')"
                @focus="testColumn($event, row, 'focus', 'fixTimeLength')"
                maxlength="250"
              />

              <span v-if="row.fixTimeCode !== 0">{{ row.fixTimeSonName }}</span>

              <el-select
                v-if="row.fixTimeCode === 0"
                class="ccui-form-longInput"
                v-model="row.fixTimeSonCode"
                placeholder="请选择"
                @change="handleChange(row, $index, 'fixTimeSonName')"
              >
                <el-option
                  v-for="item in jsList.fixTimeEnum1"
                  :key="item.dicKey"
                  :label="item.dicValue"
                  :value="item.dicKey"
                >
                </el-option>
              </el-select>
              <el-date-picker
                v-if="row.fixTimeCode === 3"
                v-model="row.datePicker"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
              />
            </template>
          </el-table-column>

          <el-table-column prop="materialName" label="付款方式" width="420">
            <template slot-scope="{ row, $index }">
              <el-radio-group
                v-model="row.payTypeCode"
                @change="handleChange(row, $index, 'payType')"
              >
                <el-radio
                  v-for="item in jsList.payTypeEnum"
                  :key="item.dicKey"
                  :label="item.dicKey"
                  >{{ item.dicValue }}</el-radio
                >
              </el-radio-group>
            </template>
          </el-table-column>

          <el-table-column prop="materialName" label="付款比率" width="420">
            <template slot-scope="{ row }">
              <div class="bl-checkbox">
                付
                <input
                  class="el-input__inner pay-input"
                  type="text"
                  v-model.lazy="row.payRate"
                  @blur="testColumn($event, row, 'blur', 'payRate')"
                  @focus="testColumn($event, row, 'focus', 'payRate')"
                  maxlength="20"
                />
                %

                <!-- 预付款不显示 -->
                <el-checkbox-group
                  v-if="row.fixTimeCode !== 5"
                  v-model="row.isRetentionMoney"
                  :max="1"
                  style="padding-left: 10px"
                >
                  <el-checkbox
                    v-for="item in jsList.paymentRatio"
                    :key="item.dicKey"
                    :label="item.dicKey"
                    >{{ item.dicValue }}</el-checkbox
                  >
                </el-checkbox-group>

                <!-- 预付款显示 -->
                <span v-if="row.fixTimeCode === 5" class="no-advance"
                  >(预付款不计入付款比例)</span
                >
              </div>
            </template>
          </el-table-column>

          <el-table-column label="操作">
            <template slot-scope="{ $index }">
              <el-button
                v-if="$index !== 0"
                @click.native.prevent="deleteRow(item, $index)"
                type="text"
                size="small"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import jsList from "../js/indexco";
import { formatNumber, proxyDateFormat, numberToChinese } from "@/basa/utils";
import { cloneDeep } from "lodash";
export default {
  name: "paymentMode",
  props: {
    detail: {
      type: Object,
      default: () => {}
    },
    // 是否是变更页面引用
    isChange: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      jsList,
      payList: [
        {
          smpPayTypeBO: {
            payType: 0,
            payTypeName: "发票"
          },
          smpPayTypeItemBOS: [
            {
              fixTimeCode: 1,
              fixTime: "按月",
              isRetentionMoney: [],
              payType: "银行承兑",
              payTypeCode: 0,
              fixTimeLength: "",
              fixTimeSonCode: 1,
              fixTimeSonName: "月",
              payRate: ""
            }
          ]
        }
      ],
      subMitStatus: false
    };
  },
  created() {
    this.init();
  },
  methods: {
    init() {
      if (
        ((!this.isChange && this.detail.state === "edit") || this.isChange) &&
        this.detail?.payTypeListBOS?.length
      ) {
        this.payList = this.detail.payTypeListBOS.map(n => ({
          smpPayTypeBO: {
            ...n.smpPayTypeBO,
            payType: n.smpPayTypeBO?.payType
          },
          smpPayTypeItemBOS: n.smpPayTypeItemBOS.map(m => ({
            ...m,
            payRate: m.payRate ? Number(m.payRate).toFixed(2) : m.payRate,
            datePicker: m.fixTimeCode === 3 ? m.fixTimeLength : "",
            endDate: m.endDate ? proxyDateFormat(m.endDate) : "",
            isRetentionMoney:
              m.isRetentionMoney !== null && [0, 1].includes(m.isRetentionMoney)
                ? [m.isRetentionMoney]
                : []
          }))
        }));
      }
    },

    // 表格input校验
    testColumn(e, row, eventType, nameModel) {
      switch (eventType) {
        case "blur":
          e.target.style.border = `1px solid ${
            row[nameModel] ? "#ccc" : "red"
          }`;

          if (nameModel === "fixTimeLength") {
            row[nameModel] = /^[0-9]*[1-9][0-9]*$/.test(row[nameModel])
              ? row[nameModel]
              : "";
          }

          // 截取小数后位数
          if (row[nameModel] && ["payRate"].includes(nameModel)) {
            row[nameModel] = formatNumber(Number(row[nameModel]), 2);
          }

          // 清空不符合规则的输入框参数
          if (!this.getInputRule(row.fixTimeLength)) {
            row.fixTimeLength = "";
          }
          if (!this.getInputRule(row.payRate)) {
            row.payRate = "";
          }
          break;
        case "focus":
          e.target.style.border = "1px solid #0089EF";
          break;
        default:
          break;
      }

      // 重置预付款的比率
      if (
        nameModel === "payRate" &&
        row.fixTimeCode === 5 &&
        row.payRate > 100
      ) {
        row.payRate = 100;
      }
    },

    // 给表头加必选标识
    must({ column }) {
      if (this.getPayTableHeadRuleNode.includes(column.label)) {
        return "must";
      }
    },

    // 添加支付块
    addPayBlock() {
      this.payList.push({
        smpPayTypeBO: {
          payType: 0,
          payTypeName: "发票",
          isChangeFlag: 1
        },
        smpPayTypeItemBOS: [
          {
            fixTime: "按月",
            fixTimeCode: 1,
            payType: "银行承兑",
            payTypeCode: 0,
            fixTimeLength: "",
            fixTimeSonCode: 1,
            fixTimeSonName: "月",
            payRate: "",
            isRetentionMoney: [],
            isChangeFlag: 1
          }
        ]
      });
    },

    // 删除支付块
    removePayBlock(index) {
      this.payList.splice(index, 1);
    },

    // 添加行
    addRow(index) {
      this.payList[index].smpPayTypeItemBOS.push({
        fixTime: "上次支付后",
        fixTimeCode: 0,
        payType: "银行承兑",
        payTypeCode: 0,
        fixTimeLength: "",
        fixTimeSonCode: 0,
        fixTimeSonName: "月",
        payRate: "",
        isRetentionMoney: [],
        isChangeFlag: 1
      });
    },

    // 删除行
    deleteRow(parentItem, i) {
      parentItem.smpPayTypeItemBOS.splice(i, 1);
    },

    handleChange(row, index, type) {
      switch (type) {
        case "fixTime":
          row.fixTime = jsList[
            index === 0 ? "onceFixTimeEnum" : "fixTimeEnum"
          ].find(_ => _.dicKey === row.fixTimeCode).dicValue;

          if ([1, 2, 4].includes(row.fixTimeCode)) {
            row.fixTimeSonName = jsList.fixTimeMap[row.fixTimeCode];
            row.fixTimeSonCode = row.fixTimeCode;
          } else {
            row.fixTimeSonCode = "";
            row.fixTimeSonName = "";
          }

          // 清空已选择或已填写的数值
          row.fixTimeLength = "";
          row.isRetentionMoney = [];
          break;

        case "fixTimeSonName":
          row.fixTimeSonName = jsList.fixTimeEnum1.find(
            _ => _.dicKey === row.fixTimeSonCode
          ).dicValue;
          break;

        case "advanceCharge":
          row.fixTime = jsList.advanceChargeEnum.find(
            _ => _.dicKey === row.fixTimeCode
          ).dicValue;
          break;

        default:
          row[`${type}`] = jsList[`${type}Enum`].find(
            _ => _.dicKey === row[`${type}Code`]
          ).dicValue;
          break;
      }
    },

    handleRadioChange(parentIndex, val) {
      const tempName = this.jsList.paymentModeTop.find(_ => _.dicKey === val)
        .dicValue;
      this.payList[parentIndex].smpPayTypeBO.payTypeName = tempName;
    },

    // 提交验证
    handleSubmit() {
      return new Promise((resolve, reject) => {
        if (this.payList.length) {
          // 每个付款条件的子项
          const payTypeItemArr = this.payList
            .map(n => n.smpPayTypeItemBOS)
            .flat(Infinity);

          // 第一列的输入框
          const fixTimeLengthStatus = payTypeItemArr.some(
            _ => ![3, 5].includes(_.fixTimeCode) && !_.fixTimeLength
          );
          // 第一列的时间框
          const datePickerStatus = payTypeItemArr.some(
            _ => _.fixTimeCode === 3 && !_.datePicker
          );

          if (fixTimeLengthStatus || datePickerStatus) {
            this.$showErrorMessage(
              "付款方式中规定时间填写不完整，请编辑后保存！"
            );
            reject("fifth");
            return;
          }
          // 预付款只能有一行.如果预付款为100%。支付次数只能有一行，否则，除了预付款之外的行相加必须等于100

          // 付款比率判空 start
          const fixTimeEmptyStatus = payTypeItemArr.some(_ => _.payRate === "");
          const fixTimeStatus = payTypeItemArr.some(_ => _.payRate === "0.00");

          if (fixTimeEmptyStatus) {
            this.$showErrorMessage("付款方式中的付款比率不能为空");
            this.subMitStatus = false;
            reject("fifth");
            return;
          }

          if (fixTimeStatus) {
            this.$showErrorMessage("付款方式中的付款比率不能 0");
            this.subMitStatus = false;
            reject("fifth");
            return;
          }
          // 付款比率判空 end

          for (let i = 0; i < this.payList.length; i++) {
            const smpPayTypeItemArr = this.payList[i].smpPayTypeItemBOS;

            const beforePay = smpPayTypeItemArr.filter(
              n => n.fixTimeCode === 5
            );
            if (beforePay.length > 1) {
              this.showPaymentModeError(i, "每个付款条件只能有一条预付款！");
              reject("fifth");
              return;
            }

            const tempFixTimeCode = smpPayTypeItemArr.filter(
              n => n.fixTimeCode !== 5
            );

            const payRateItem = smpPayTypeItemArr.find(
              n => n.fixTimeCode === 5
            );

            if (payRateItem) {
              if (payRateItem.payRate !== "100.00") {
                const payRateSum = tempFixTimeCode.reduce(
                  (pre, cur) =>
                    new this.$BigNumber(Number(pre)).plus(Number(cur.payRate)),
                  0
                );

                if (payRateSum.toNumber() !== 100) {
                  this.showPaymentModeError(
                    i,
                    "每个付款条件的付款比率总和必须等于 100% (预付款除外)"
                  );
                  reject("fifth");
                  break;
                } else {
                  this.subMitStatus = true;
                }
              } else {
                this.subMitStatus = true;
              }
            } else {
              const payRateSum = tempFixTimeCode.reduce(
                (pre, cur) =>
                  new this.$BigNumber(Number(pre)).plus(Number(cur.payRate)),
                0
              );

              if (payRateSum.toNumber() === 100) {
                this.subMitStatus = true;
              } else {
                this.showPaymentModeError(
                  i,
                  "每个付款条件的付款比率总和必须等于 100% (预付款除外)"
                );
                reject("fifth");
                break;
              }
            }
          }

          if (this.subMitStatus) {
            const payListParams = cloneDeep(this.payList);
            const params = payListParams.map(n => ({
              ...n,
              smpPayTypeItemBOS: n.smpPayTypeItemBOS.map(m => ({
                ...m,
                fixTimeLength:
                  m.fixTimeCode === 3 ? m.datePicker : m.fixTimeLength,
                isRetentionMoney: m.isRetentionMoney.length
                  ? m.isRetentionMoney[0]
                  : ""
              }))
            }));
            resolve(params);
          }
        } else {
          reject("fifth");
        }
      });
    },

    //暂存
    beforeSubmitTemp() {
      return new Promise((resolve, reject) => {
        if (this.payList.length) {
          const params = this.payList.map(n => ({
            ...n,
            smpPayTypeItemBOS: n.smpPayTypeItemBOS.map(m => ({
              ...m,
              fixTimeLength:
                m.fixTimeCode === 3 ? m.datePicker : m.fixTimeLength,
              isRetentionMoney: m.isRetentionMoney.length
                ? m.isRetentionMoney[0]
                : ""
            }))
          }));
          resolve(params);
        }
      });
    },

    showPaymentModeError(index, message) {
      this.$showErrorMessage(
        `第 ${numberToChinese(index + 1)} 组付款方式中${message}`
      );
      this.subMitStatus = false;
    },

    getInputRule(val) {
      const reg = /(^(\d{0,11})\.(\d{0,8})$)|(^\d{0,20}$)/;
      return reg.test(val);
    }
  },
  computed: {
    ...mapGetters(["getPayTableHeadRuleNode"])
  }
};
</script>

<style lang="scss" scoped>
/deep/ .ccui-multifunctional-table-wrapper {
  .el-table__fixed-right,
  .el-table__fixed {
    height: 100% !important;
  }
  .el-table td,
  .el-table th.is-leaf {
    border-right: 1px solid #edf2fc;
  }
}
.radio-group {
  padding-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.el-select {
  width: 120px;
  // margin-right: 10px;
}
.el-input {
  width: 60px;
}
.el-date-editor.el-input {
  width: 150px;
  margin: 0 10px;
}
.bl-checkbox {
  display: flex;
  align-items: center;
}
/deep/ .el-table__fixed-right {
  height: 100% !important;
}
/deep/ .el-table th.must > .cell:before {
  content: "*";
  color: #ff1818;
  margin-right: 5px;
}
.pay-block + .pay-block {
  margin-top: 20px;
}
.no-advance {
  margin-left: 20px;
  color: red;
}
.pay-input {
  width: 70px;
  margin: 0 10px;
}
</style>
